package com.missilike.biz.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.missilike.biz.IMilJournalDetailService;
import com.missilike.domain.mapper.MilJournalInfoMapper;
import com.missilike.domain.response.MilJournalInfo;
import com.missilike.repository.entity.MilJournal;
import com.missilike.repository.entity.MilJournalDetail;
import com.missilike.repository.mapper.MilJournalMapper;
import com.missilike.biz.IMilJournalService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 期刊 服务实现类
 * </p>
 *
 * @author kin
 * @since 2019-01-14
 */
@Service
public class MilJournalServiceImpl extends ServiceImpl<MilJournalMapper, MilJournal> implements IMilJournalService {

    private final IMilJournalDetailService milJournalDetailService;

    @Autowired
    public MilJournalServiceImpl(IMilJournalDetailService milJournalDetailService) {
        this.milJournalDetailService = milJournalDetailService;
    }

    @Override
    public Page<MilJournalInfo> getList(IPage<MilJournal> page) {
        IPage<MilJournal> journalList = this.page(page, null);
        Page<MilJournalInfo> milJournalInfoPage = MilJournalInfoMapper.MAPPER.pageConvert(journalList);

        if (CollectionUtils.isNotEmpty(journalList.getRecords())) {
            List<Integer> journalIds = journalList.getRecords()
                    .stream()
                    .map(MilJournal::getId)
                    .collect(Collectors.toList());

            Collection<MilJournalDetail> milJournalDetails = milJournalDetailService.list(new QueryWrapper<MilJournalDetail>()
                    .lambda()
                    .in(MilJournalDetail::getJournalId, journalIds)
            );

            milJournalInfoPage.getRecords().forEach(journal ->
                    journal.setMilJournalDetailList(milJournalDetails.stream()
                            .filter(x -> x.getJournalId().equals(journal.getId()))
                            .collect(Collectors.toList())
                    ));
        }
        return milJournalInfoPage;
    }
}
